package com.yonyou.ucf.mdf.app.mobile.module;

import com.alibaba.fastjson.JSONObject;
import com.yonyou.iuap.context.InvocationInfoProxy;
import com.yonyou.ucf.mdf.app.mobile.MobileProperties;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.isv.router.module.isvrequest.ISVRequest;
import com.yonyoucloud.iuap.ucf.mdd.starter.ucg.openapi.isv.router.module.isvrequest.ISVRequestBody;
import java.util.HashMap;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


/**
 * 本类主要用于
 *
 * @author liuhaoi
 * @since Created At 2020/7/2 11:33 上午
 */
@Slf4j
@Service
public class MobileTemplateServiceImpl implements MobileTemplateService {

    private static final String PATH_MOBILE_EXISTS = "registered/isPageBillNo?billNo=%s&tenantId=%s";

    private final MobileProperties properties;
    private final RestTemplate restTemplate;
    private final ISVRequest isvRequest;

    public MobileTemplateServiceImpl(MobileProperties properties, ApplicationContext context,
        ISVRequest isvRequest) {
        this.properties = properties;
        restTemplate = new MobileRestTemplate(1000L, 3000L, 300, 100, context).getRestTemplate();
        this.isvRequest = isvRequest;
    }

    @Override
    public boolean exists(String billNum, String tenantId) {

        String appMenuListHost = properties.getAppMenuListHost();
        String split;
        if (appMenuListHost.endsWith("/")) {
            split = "";
        } else {
            split = "/";
        }
        String url = appMenuListHost + split + String.format(PATH_MOBILE_EXISTS, billNum, tenantId);

        HashMap<String, String> headers = new HashMap<>();
        headers.put(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);
        ISVRequestBody isvRequestBody = new ISVRequestBody();
        isvRequestBody.setUrl(url);
        isvRequestBody.setRequestMethod("GET");
        isvRequestBody.setHeaders(headers);
        String result = isvRequest.doRequest(InvocationInfoProxy.getTenantid(),isvRequestBody);
        log.info("返回结果 :{}" + result);
        Response body = JSONObject.parseObject(result,Response.class);
        if (body != null && body.getData() != null) {
            ResponseData data = body.getData();
            return data.getInfo() != null && data.getInfo();
        }
        return false;
    }


    @Data
    public static class Response {
        private Integer code;
        private String message;
        private ResponseData data;
    }

    @Data
    public static class ResponseData {
        private Boolean info;
    }

}
